package behavioral.pattern.myiteratior;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;

/**
 * @Autor: yuanyongan
 * @Description:
 * @Date 2023/1/10 9:26
 */
public class MyArrayIterator<T> implements MyIterator<T>{
    private int cursor;
    private final ArrayList<T> arrayList;
    public MyArrayIterator(ArrayList<T> arrayList){
        this.cursor = 0;
        this.arrayList = arrayList;
    }

    @Override
    public boolean hasNext() {
        return cursor < arrayList.size();
    }

    @Override
    public void next() {
        cursor++;
    }

    @Override
    public T currentItem() {
        if (cursor >= arrayList.size()){
            throw new NoSuchElementException();
        }
        return arrayList.get(cursor);
    }

    @Override
    public void remove() {
        if (cursor < 0){
            throw new IllegalStateException();
        }
        try {
            arrayList.remove(cursor);
            cursor--;

        }catch (IndexOutOfBoundsException ex){
            throw new ConcurrentModificationException();
        }
    }
}
